package com.dragon.modules.yuegou.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.entity.system.ApplicationEntity;
import com.dragon.modules.yuegou.enums.YsqAppType;
import com.dragon.modules.yuegou.enums.code.BusinessCode;
import com.dragon.modules.yuegou.enums.code.PayCode;
import com.dragon.modules.yuegou.enums.code.SystemCode;
import com.dragon.modules.yuegou.enums.system.ApplicationType;
import com.dragon.modules.yuegou.mapper.system.ApplicationMapper;
import com.dragon.modules.yuegou.model.system.Address;
import com.dragon.modules.yuegou.model.system.Application;
import com.dragon.modules.yuegou.properties.PostersProperties;
import com.dragon.modules.yuegou.query.system.ApplicationQuery;
import com.dragon.modules.yuegou.service.busd.DistrictService;
import com.dragon.modules.yuegou.service.busd.GroupService;
import com.dragon.modules.yuegou.service.system.ApplicationService;
import com.dragon.modules.yuegou.utils.AppUtils;
import com.dragon.modules.yuegou.web.Check;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 前端应用管理 服务实现
 *
 * @author pbuilder generated
 * @date 2019-05-07 11:01:06
 * @version 2.0
 */
@Service("sysApplicationService")
public class ApplicationServiceImpl  extends ServiceImpl<ApplicationMapper, ApplicationEntity> implements ApplicationService {


	@Autowired
	private GroupService groupService;

	@Autowired
	private PostersProperties postersProperties;
	
	@Autowired
	private DistrictService districtService;


	@Override
	public Application getByAppid(@NotEmpty String appid) {
		Check.notEmpty(appid, PayCode.APPID_IS_EMPTY.getMessage());
		ApplicationEntity app = getById(appid);
		if(app == null) {
			throw new DragonException(99999,"非法应用ID：" + appid);
		}
		return new Application(app);
	}

	@Override
	public Application getByWxAppid(@NotEmpty String wxAppid) {
		Check.notEmpty(wxAppid, PayCode.APPID_IS_EMPTY.getMessage());
		ApplicationQuery query = new ApplicationQuery();
		query.appid().eq(wxAppid);
		List<ApplicationEntity> app = baseMapper.selectList(query.toQueryWrapper());
		if(CollectionUtils.isEmpty(app)) {
			throw new DragonException(99999,"非法微信应用ID：" + wxAppid);
		}
		return new Application(app.get(0));
	}
	
	@Override
	public IPage<Application> search(PageRequest page, ApplicationQuery query) {
		IPage<ApplicationEntity> pageEntity = new Page<>(page.getPage(), page.getSize(), page.getCount());
		IPage<ApplicationEntity> pageEntites = baseMapper.selectPage(pageEntity, query.toQueryWrapper());
		return pageEntites.convert(Application::new);
	}

	@Override
	public void saveAppLication(Application application) {
		ApplicationQuery applicationQuery = new ApplicationQuery();
		applicationQuery.setName(application.getName());
		QueryWrapper<ApplicationEntity> qw = applicationQuery.toQueryWrapper();
		qw.orderByAsc(Address.COL_ADCODE);

		List<ApplicationEntity> entities = baseMapper.selectList(qw);
		List<Application> list =entities.stream().map(Application::new).collect(Collectors.toList());

		if (StringUtils.isEmpty(application.getId())) {
			if (list.size()>0) {
				throw new DragonException(SystemCode.APPLET_NAME_NO_REPEATED);
			}
			//添加小程序
			application.setId(nextId(application.getType()));
			baseMapper.insert(application);
		}else {
			if (list.size()>0 && !list.get(0).getId().equals(application.getId()) ) {
				throw new DragonException(SystemCode.APPLET_NAME_NO_REPEATED);
			}
			//修改小程序
			baseMapper.updateById(application);
		}
	}

	@Override
	public Application getOriginalId(String busdId) {
		String miniAppid = groupService.getMiniAppIdByBusdId(busdId);
		ApplicationQuery applicationQuery = new ApplicationQuery();
		applicationQuery.appid().eq(miniAppid);
		QueryWrapper<ApplicationEntity> qw = applicationQuery.toQueryWrapper();
		qw.orderByAsc(Address.COL_ADCODE);

		List<ApplicationEntity> entities = baseMapper.selectList(qw);

		Application application = null;
		if (CollectionUtils.isNotEmpty(entities)) {
			application = new Application(entities.get(0));
		}else {
			application = new Application();
		}

		if (!StringUtils.isEmpty(application.getOriginalid())) {
			application.setOriginalid(postersProperties.getDefaultOriginalId());
		}
		return application;
	}
	
	@Override
	public Application getAppConfig(String busdId) {
		Check.notNull(busdId, BusinessCode.BUSDID_NOTNULL.getMessage());
		String appId =districtService.getAliAppId(busdId);
		if(!StringUtils.isEmpty(appId)) {
			ApplicationQuery query = new ApplicationQuery();
			query.setAppid(appId);
			List<ApplicationEntity> app = baseMapper.selectList(query.toQueryWrapper());
			if(CollectionUtils.isNotEmpty(app)) {
				return new Application(app.get(0));
			}
		}
		return null;
	}

	private String nextId(ApplicationType type) {
		Check.notNull(type, "必须提供应用类型");
		Long maxId = baseMapper.getMaxIdByType(type.getCode());
		if(maxId == null) {
			YsqAppType globalType = convert(type);
			return AppUtils.firstAppid(globalType);
		}else {
			return AppUtils.nextAppid(maxId);
		}
	}
	
	private YsqAppType convert(ApplicationType type) {
		// XXX 最好统一应用类型
		switch(type) {
		/*悦购*/
		case YGIRL:
			return YsqAppType.YSQ_XCX;
		/*悦荷包*/
		case WALLET:
			return YsqAppType.YSQ_WALLET_XCX;
		/*悦商管*/
		case YSQ:
			return YsqAppType.YSQ_GROUP_XCX;
		/*悦商惠*/
		case YSH:
			return YsqAppType.YSQ_MERCHANT_XCX;
		/*员工版*/
		case YGB:
			return YsqAppType.YSQ_GROUP_EMPLOYEE_XCX;
		/*安卓*/
		case ANDROID:
			return YsqAppType.YSQ_APP_ANDROID;
		/*苹果*/
		case IOS:
			return YsqAppType.YSQ_APP_IOS;
		/*大运营版*/
		case PLATFORM:
			return YsqAppType.YSQ_PLATFORM;
		/*集团版*/
		case GROUP:
			return YsqAppType.YSQ_GROUP;
		default:
			throw new DragonException(10000,String.format("未知应用类型：%s，改动应用类型的时候是否遗漏了此处？", type.getAlias()));
		}
	}



}